package com.binguo.helper;

import com.alibaba.fastjson.JSON;
import com.binguo.common.exception.ServiceException;
import com.binguo.entity.FaceConfidence;
import com.qcloud.image.ImageClient;
import com.qcloud.image.request.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;

import static com.binguo.common.exception.ErrorCode.PERSON_EXISTS;
import static com.binguo.common.exception.ErrorCode.UPLOAD_ERROR;


/**
 */
@Component
public class FaceHelperV22 {

    private static Logger logger = LoggerFactory.getLogger(FaceHelperV2.class);


//    @Value("youtu.appid")
//    private String APP_ID;
//    @Value("youtu.secretID")
//    private String SECRET_ID;
//    @Value("youtu.secretKey")
//    private String SECRET_KEY;
//    @Value("youtu.userId")
//    private String USER_ID;


    String appId = "1257123484";
    String secretId = "AKIDud6KAoFVVHrDLFCLYXIp8B0aCZpql7NN";
    String secretKey = "tXv3wZ0B9sMwNacR2PYUCftsfDk49yYs";
    String bucketName = "";
    ImageClient imageClient;

    //fixme haibang 1.只能新建一个person，添加该个体的其他图片调用http://api.youtu.qq.com/youtu/api/addface
    //fixme haibang 2.personId 为groupId_customerId,确保唯一性



    public FaceHelperV22(){
        imageClient = new ImageClient(appId, secretId, secretKey, ImageClient.NEW_DOMAIN_recognition_image_myqcloud_com);
        logger.info("======================================imageClient = {}", imageClient);
    }

    /**
     * 创建人脸识别信息
     * personId 为groupId_customerId,确保唯一性
     * @return faceId
     */
    public String newPerson(String url, String personId, String groupId){

        try {
            String[] addFaceUrlList = new String[1];
            addFaceUrlList[0] = groupId;

            FaceNewPersonRequest personNewReq = new FaceNewPersonRequest(bucketName, personId, addFaceUrlList, url, "", "");
            String res = imageClient.faceNewPerson(personNewReq);

            JSONObject object = _handleResponse(res);
            return (String)object.get("face_id");
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ServiceException(UPLOAD_ERROR);
        }
    }

    /**
     * 人脸识别
     * @return 候选人
     */
    public FaceConfidence faceIdentify(String url, String groupId){
        FaceIdentifyRequest faceIdentifyReq = new FaceIdentifyRequest(bucketName, groupId, url);// 一个 groupId
        //FaceIdentifyRequest  faceIdentifyReq = new FaceIdentifyRequest(bucketName, groupIds, faceImageUrl);// 多个 groupId
        JSONObject object = _handleResponse(imageClient.faceIdentify(faceIdentifyReq));
        return JSON.parseObject(object.toString(), FaceConfidence.class);
    }

    /**
     * 人脸识别
     * @return 候选人
     */
    public FaceConfidence faceIdentifyBase64(String urlBase64, String groupId){
        FaceIdentifyRequest faceIdentifyReq = new FaceIdentifyRequest(bucketName, groupId,
                java.util.Base64.getDecoder().decode(urlBase64));// 一个 groupId
        faceIdentifyReq.setImage(new File("/var/www/tomcat/yp/a.jpg"));
//        faceIdentifyReq.setImage(new File(FaceHelperV2.class.getResource("/").getFile() + "/a.jpg"));
        //FaceIdentifyRequest  faceIdentifyReq = new FaceIdentifyRequest(bucketName, groupIds, faceImageUrl);// 多个 groupId
        JSONObject object = _handleResponse(imageClient.faceIdentify(faceIdentifyReq));
        return JSON.parseObject(object.toString(), FaceConfidence.class);
    }

    /**
     *
     * 删除个体
     * @return
     */
    public void deletePerson(String persionId){
        try{
            FaceDelPersonRequest delPersonReq = new FaceDelPersonRequest(bucketName, persionId);

            _handleResponse(imageClient.faceDelPerson(delPersonReq));
        } catch (Exception e){
            logger.info(e.getMessage());
            e.printStackTrace();
            throw new ServiceException("删除人脸失败");
        }



    }

    /**
     * 添加人脸识别信息
     * personId 为groupId_customerId,确保唯一性
     * @return faceId
     */
    public String addPerson(String url, String personId){
        try{

            FaceAddFaceRequest addFaceRequest = new FaceAddFaceRequest(bucketName, new String[]{url}, personId, "");

            JSONObject object = _handleResponse(imageClient.faceAddFace(addFaceRequest));
            JSONArray jsonArray = (JSONArray) object.get("face_ids");
            return jsonArray.getString(0);
        } catch (Exception e){
            logger.info(e.getMessage());
            e.printStackTrace();
        }

        return null;

    }



    /**
     * 删除人脸识别信息
     * personId 为groupId_customerId,确保唯一性
     * @return faceId
     */
    public boolean delFace(String personId, String faceId){
        try{
            logger.info("faceHelperv2.delFace1");
            logger.info("faceHelperv2.delFace2");

            FaceDelFaceRequest delFaceRequest = new FaceDelFaceRequest(bucketName, personId, new String[]{faceId});
            logger.info("faceHelperv2.delFace3");

            _handleResponse(imageClient.faceDelFace(delFaceRequest));
            logger.info("faceHelperv2.delFace4");

            return true;
        } catch (Exception e){
            logger.info("faceHelperv2.delFace5");
            logger.info(e.getMessage());
            e.printStackTrace();
        }

        return false;
    }


    private JSONObject _handleResponse(String res){
        try {
            JSONObject response = new JSONObject(res);
            Integer code = (Integer) response.get("code");
            String msg = (String) response.get("message");
            if(code == 0) {
                return response.getJSONObject("data");
            }else if(code == -1302){
                throw new ServiceException(PERSON_EXISTS);
            } else {
                logger.info("腾讯人脸response发现错误, errorcode:" + code + ", errormsg: " + msg);
                throw new ServiceException(msg);
            }
        } catch (JSONException e) {
            throw new ServiceException(UPLOAD_ERROR);
        }
    }
/*
    public static void main(String[] args) {
        FaceIdentifyRequest faceIdentifyReq = new FaceIdentifyRequest("",
                WxFaceService.groupId,
//                new File("/Users/jay/IdeaProjects/pmpsh/yunpeng/appapi/target/WechatIMG667.jpeg")
//                new File("/Users/jay/IdeaProjects/pmpsh/yunpeng/appapi/src/main/resources/a.jpg")
                new File("/Users/jay/IdeaProjects/pmpsh/yunpeng/appapi/target/WechatIMG689.jpeg")

        );// 一个 groupId


        FaceHelperV2 faceHelperV2 = new FaceHelperV2();
        JSONObject object = faceHelperV2._handleResponse(faceHelperV2.imageClient.faceIdentify(faceIdentifyReq));

        System.out.println(object);
    }*/
}
